<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="user_id" label="发起用户" required>
        <uni-data-picker v-model="formData.user_id" collection="uni-id-users" where="(role=='merchant'||role=='user') && status==0" field="nickname as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="deposit_account_id" label="提款账户" required>
        <uni-data-picker v-model="formData.deposit_account_id" :localdata="deposit_account_localdata"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="terminal_type" label="终端类型" v-if="user_role_type!=''">
        <uni-data-checkbox v-model="formData.terminal_type" mode="button" :localdata="formOptions.terminal_type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item  label="账户余额" >
        <div style="font-weight: bold;color: #04c124;">
            {{ BigJs(wallet_amount.available_amount).div(100).toFixed(2)  }}元
        </div>
      </uni-forms-item>
      <uni-forms-item name="withdraw_amount" label="提现金额" required>
        <uni-easyinput placeholder="提现金额最多小数点两位，单位元" type="number" v-model="formData.withdraw_amount"></uni-easyinput>
        <div class="input_tail">
          本次最多可提现: {{ BigJs(wallet_amount.available_amount).div(100).toFixed(2) }} 元
        </div>
      </uni-forms-item>
      <uni-forms-item name="verification_code" label="动态密码" required>
        <uni-easyinput type="text" placeholder="请输入6位数动态密码" :maxlength="6" v-model="formData.verification_code" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="withdraw_remark" label="提现附言">
        <uni-easyinput type="textarea" placeholder="提现附言" v-model="formData.withdraw_remark" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="operator_remark" label="操作备注">
        <uni-easyinput type="textarea" placeholder="操作备注" v-model="formData.operator_remark" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="withdraw_status" label="提现状态">
        <uni-data-checkbox v-model="formData.withdraw_status" mode="button" :localdata="formOptions.withdraw_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <button class="uni-button" style="width: 100px;margin-left: 15px;" @click="closeAll">关闭</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food-withdraw-list.js';
  import {BANK_NAME_TOGGLE}  from '~@/common/bank-class.js'
  import {enumConverter}  from '../../../food-withdraw-mode/js_sdk/validator/food-withdraw-mode.js'
  import BigJs from 'big.js'

  const excludeFieds=[`operator_id`]
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-withdraw-list';

  function getValidator(fields) {
    let result = {}
    fields=fields.filter(it=>{
      return !excludeFieds.includes(it)
    })
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "merchant_id": "",
        "user_id": "",
        "operator_id": "",
        "deposit_account_id": "",
        "withdraw_amount": null,
        "withdraw_remark": "",
        "operator_remark": "",
        "withdraw_status": 0,
        "terminal_type": 0,
        verification_code:``,
        "last_update_date": null
      }
      return {
        deposit_account_localdata:[],
        user_role_type:``,
        wallet_amount:{
          available_amount:`0.00`,
          freeze_amount:`0.00`
        },

        formData,
        formOptions: {
          "withdraw_status_localdata": [
            {
              "value": 0,
              "text": "出款成功"
            },
            {
              "value": 1,
              "text": "正在审核"
            },
            {
              "value": 2,
              "text": "提款拒绝"
            },
            {
              "value": 3,
              "text": "正在出款"
            },
            {
              "value": 4,
              "text": "出款失败"
            }
          ],
          "terminal_type_localdata": [
            {
              "value": 0,
              "text": "商户"
            },
            {
              "value": 1,
              "text": "骑手"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      'formData.user_id'(value){
        this.getLocaldata(value);
        this.getUserWallet(value)
      },
    },
    mounted() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      init(id){
        console.log(id)
        this.formDataId = id
        this.getDetail(id)
      },
      closeAll(){
        this.$emit(`manualClose`,`addComponent`)
      },
      BigJs(args){
        return new BigJs(args)
      },
      async getUserWallet(userId){
        const {result:{ data:[userInfo] }}=await db.collection(`uni-id-users`)
        .where({
          _id:userId
        })
        .field(`role,merchant_id`)
        .get()
        if(userInfo==null){
            return layer.msg(`该用户为异常用户，请联系管理员`, { icon : 2, time: 1500})
        }
        const roleStr=userInfo.role.join();
        const toggleField={
          user:{
            table:``,
            field:``,
            whereFilter:{
              
            },
            valueId:1,
            extract:(_db_data)=>{
              return {}
            }
          },
          merchant:{
            table:`food-merchant-list`,
            field:`merchant_money_amount`,
            whereFilter:{
              _id:userInfo.merchant_id
            },
            valueId:0,
            extract:(_db_data)=>{
              return _db_data.merchant_money_amount
            }
          }
        }
        const { table,field,valueId,whereFilter,extract } =toggleField[roleStr]
        if(table===``){
          return layer.msg(`该用户暂不持支提现，请联系管理员`, { icon : 2, time: 1500})
        }
        this.user_role_type=roleStr;
        this.formData.terminal_type=valueId
        const {result:{data:[walletInfo]} } = await db.collection(table)
        .where(whereFilter)
        .field(field)
        .get();
        this.wallet_amount=extract(walletInfo)

      },
      async getLocaldata(userId){
        const {result:{ data }}=await db.collection(`food-withdraw-mode`)
        .where({
          user_id:userId,
          enable_status:true
        })
        .get()
        this.deposit_account_localdata=data.map(it=>{
          let selectText=`${ enumConverter.pay_mode_valuetotext[it.pay_mode] }`
          if(it.pay_mode==1){
            selectText=`${ enumConverter.pay_mode_valuetotext[it.pay_mode] } -  ${it.bank_account_name} - ${BANK_NAME_TOGGLE[it.bank_terminal_name]} - ${it.bank_number}`
          }
          return {
            text:selectText,
            value:it._id
          }
        })

      },

      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          if(isNaN(res.withdraw_amount)||res.withdraw_amount==''){
            return layer.msg(`请输入正确的提款金额，最多小数点两位`, { icon : 2, time: 1500})
          }
          const withdraw_amount= parseFloat(res.withdraw_amount);
          if(!/^\d+(\.\d{1,2})?$/.test(withdraw_amount+'')){
            return layer.msg(`请输入正确的提款金额，最多小数点两位`, { icon : 2, time: 1500})
          }
          if(withdraw_amount<=0){
            return layer.msg(`提款金额必须大于0`, { icon : 2, time: 1500})
          }

          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.$emit(`refreshData`)
          this.closeAll();
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("merchant_id,user_id,operator_id,deposit_account_id,withdraw_amount,withdraw_remark,operator_remark,withdraw_status,terminal_type,last_update_date").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            // 将提现金额转换成元显示
            data.withdraw_amount=+BigJs(data.withdraw_amount).div(100);
            // 设置动态验证码为空
            data.verification_code=``;
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
